package com.example.secondhandshop.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.example.secondhandshop.R;
import com.example.secondhandshop.bean.Item;
import com.example.secondhandshop.model.GoodsDetailModel;

public class ItemDetailActivity extends AppCompatActivity {

    private ImageView itemImageView;
    private TextView titleTextView;
    private TextView priceTextView;
    private TextView userNameTextView;
    private TextView descriptionTextView;
    private Button chatBubbon;
    private Button purchaseButton;


    private GoodsDetailModel goodsDetailModel;
    private boolean isActivityFinishing = false;
    private Item item;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_item_detail);

        // 初始化视图
        itemImageView = findViewById(R.id.itemImage);
        titleTextView = findViewById(R.id.titleText);
        priceTextView = findViewById(R.id.priceText);
        userNameTextView = findViewById(R.id.userNameText);
        descriptionTextView = findViewById(R.id.descriptionText);
        purchaseButton = findViewById(R.id.AddOrderButton);
        chatBubbon =   findViewById(R.id.chatBubbon);

        // 获取商品ID并请求商品详情
        long itemId = getIntent().getLongExtra("itemId", -1);
        Log.d("ItemDetailActivity", "Item ID: " + itemId);
        if (itemId != -1) {
            LoadGoodsDetails(itemId);
        } else {
            titleTextView.setText("错误: 商品ID无效");
        }

        purchaseButton.setOnClickListener(view -> {
            if (item != null) { // 确保 item 已正确初始化
                Intent intent = new Intent(ItemDetailActivity.this, PurchaseActivity.class);
                Log.d("ItemDetailActivity", "Item ID: " + item.getId());
                Log.d("ItemDetailActivity", "Item Price: " + item.getPrice());
                Log.d("ItemDetailActivity", "Item Username: " + item.getUsername());
                Log.d("ItemDetailActivity", "Item Avatar: " + item.getAvatar());
                Log.d("ItemDetailActivity", "Item Imageurl: " + item.getImageUrlList().get(0));
                Log.d("ItemDetailActivity", "Item Type: " + item.getTypeName());
                Log.d("ItemDetailActivity", "buyerId " + item.getTUserId());
                intent.putExtra("itemId", item.getId()); // 传递商品信息id
                intent.putExtra("buyerId", item.getTUserId()); // 传递当前用户的id
                intent.putExtra("price", item.getPrice()); // 传递商品信息价格
                intent.putExtra("magic", item.getAvatar()); // 传递商品发布者头像
                intent.putExtra("title", item.getTypeName()); // 传递商品信息标题
                intent.putExtra("image", item.getImageUrlList().get(0)); // 传递商品信息图片
                intent.putExtra("username", item.getUsername());// 卖家用户名
                intent.putExtra(" addr;", item.getAddr());// 卖家地址
                intent.putExtra("sellerId", item.getTuserId()); // 传递卖家id

                startActivity(intent);
            } else {
                Log.e("ItemDetailActivity", "Item is null, cannot proceed to PurchaseActivity");
            }
        });


        chatBubbon.setOnClickListener(view -> {
            if (item != null) {
                Intent intent = new Intent(ItemDetailActivity.this, MessageDetails.class);//改为消息列表的activity
                Log.d("ItemDetailActivity", "Item Avatar: " + item.getAvatar());
                intent.putExtra("magic", item.getAvatar()); // 传递商品发布者头像
                System.out.println("sellerid=="+item.getTuserId());
                intent.putExtra("sellerId",(int)item.getTuserId());//卖家id
                intent.putExtra("sellername", item.getUsername());// 卖家用户名
                startActivity(intent);
            } else {
                Log.e("ItemDetailActivity", "Item is null, cannot proceed to PurchaseActivity");
            }
        });

    }

    private void LoadGoodsDetails(long itemId) {
        goodsDetailModel = new GoodsDetailModel();

        // 开始请求商品详情
        goodsDetailModel.getItems(itemId, new GoodsDetailModel.OnProductsFetchedListener() {
            @Override
            public void onFailure(String errorMessage) {
                Log.e("ItemDetailActivity", "请求失败: " + errorMessage);
                runOnUiThread(() -> {
                    if (!isActivityFinishing) {
                        titleTextView.setText("请求失败: " + errorMessage);
                    }
                });
            }

            @Override
            public void onSuccess(Item item) {
                if (item != null) {
                    ItemDetailActivity.this.item = item;
                    runOnUiThread(() -> {
                        if (!isActivityFinishing) {
                            // 更新UI
                            titleTextView.setText(item.getTypeName());
                            priceTextView.setText("￥" + item.getPrice());
                            userNameTextView.setText(item.getUsername());
                            descriptionTextView.setText(item.getContent());

                            // 加载图片
                            if (!item.getImageUrlList().isEmpty()) {
                                Glide.with(ItemDetailActivity.this)
                                        .load(item.getImageUrlList().get(0)) // 假设这里取第一张
                                        .placeholder(R.drawable.unknown_goods)
                                        .into(itemImageView);
                            }
                        }
                    });
                }
//                else {
//                    runOnUiThread(() -> {
//                        if (!isActivityFinishing) {
//                            titleTextView.setText("错误: 未知商品信息");
//                        }
//                    });
//                }
            }
        });
    }

//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        // 设置标志位为 true，表明活动正在销毁
//        isActivityFinishing = true;
//
//        // 取消网络请求
//        if (goodsDetailModel != null) {
//            goodsDetailModel.cancelPendingRequests();
//        }
//    }
}